//
//  AppDelegate.swift
//  kxf
//
//  Created by 文 on 2023/5/22.
//

import UIKit
import IQKeyboardManagerSwift
import Reachability
import MCToast

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let reachability = try! Reachability()
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        self.window?.rootViewController = WelcomeVC()
        initIQKeyBoard()
        initWeChatSDK()
        checkNetWork()
//        sendGetVersionRequest()
        
        
//        let token = UserDefaults.standard.string(forKey: whToken)
//        if token?.count ?? 0 > 1 {
//            self.window?.rootViewController = LLTabBarViewController()
//        }else{
//            self.window?.rootViewController = LoginVC()
//        }
        
//        Bugly.start(withAppId: "06dc40ed1d")
        
        return true
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        let handleUrlStr = url.absoluteString
        if let handleUrl = URL(string: handleUrlStr) {
           return WXApi.handleOpen(handleUrl, delegate: self)
        }
        return false
    }
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        let handleUrlStr = url.absoluteString
        if let handleUrl = URL(string: handleUrlStr) {
           return WXApi.handleOpen(handleUrl, delegate: self)
        }
        return false
    }
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([any UIUserActivityRestoring]?) -> Void) -> Bool {
        return WXApi.handleOpenUniversalLink(userActivity, delegate: self)
    }
    
    func switchRootViewController(to newRootVC: UIViewController) {
        let transtition = CATransition()
        transtition.duration = 0.3
        transtition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        UIApplication.shared.keyWindow?.layer.add(transtition, forKey: "animation")
        UIApplication.shared.keyWindow?.rootViewController = newRootVC

    }
}

//MARK: 微信代理方法
extension AppDelegate: WXApiDelegate {
    //MARK:微信回调
    func onResp(_ resp: BaseResp) {
        if resp.isKind(of: PayResp.self) {
         //这里是微信支付的回调
        }  else if resp.isKind(of: SendAuthResp.self)        {
         //这里是授权登录的回调
            let aresp = resp as! SendAuthResp
            DLLog(message: "onResp   ------ \(aresp.description)")
            
        } else if resp.isKind(of: SendMessageToWXResp.self) {
            if resp.errCode == WXSuccess.rawValue{
                print("分享成功")
            }else if resp.errCode == WXErrCodeCommon.rawValue {
                print("分享失败：普通错误类型")
            }else if resp.errCode == WXErrCodeUserCancel.rawValue {
                print("分享失败：用户点击取消并返回")
            }else if resp.errCode == WXErrCodeSentFail.rawValue {
                print("分享失败：发送失败")
            }else if resp.errCode == WXErrCodeAuthDeny.rawValue {
                print("分享失败：授权失败")
            }else if resp.errCode == WXErrCodeUnsupport.rawValue {
                print("分享失败：微信不支持")
            }
        }
    }
    func onReq(_ req: BaseReq) {
        DLLog(message: "onReq   ------ \(req)")
    }
 }

extension AppDelegate{
    func initIQKeyBoard(){
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        // 控制是否显示键盘上的工具条
         IQKeyboardManager.shared.enableAutoToolbar = true
        //最新版的设置键盘的returnKey的关键字 ,可以点击键盘上的next键，自动跳转到下一个输入框，最后一个输入框点击完成，自动收起键盘
         IQKeyboardManager.shared.toolbarManageBehaviour = .byPosition
    }
    func initWeChatSDK() {
        WXApi.startLog(by: .normal) { ss in
            DLLog(message: "\(ss)")
        }
        WXApi.registerApp("wx3d596e654832d4eb", universalLink: "https://app.happayment.com/ykf/")
    }
    
    func checkNetWork(){
        self.sendGetVersionRequest()
            
        reachability.whenReachable = { reachability in
            reachability.stopNotifier()
            self.sendCheckVersionRequest()
            if reachability.connection == .wifi {
                print("Reachable via WiFi")
            } else {
                print("Reachable via Cellular")
            }
        }
        reachability.whenUnreachable = { _ in
            print("Not reachable")
            let firstLoad = UserDefaults.AccountInfo.getString(forKey: .firstLoad) ?? "Y"

            if firstLoad == "Y" {
                UserDefaults.AccountInfo.set(value: "N", forKey: .firstLoad)
            }else {
                WHBaseViewVC().presentAlertVc(confirmBtn: "网络设置", message: "请确认是否已开启《星渝付助手》网络权限", title: "无网络连接", cancelBtn: "取消", handler: { (acion) in
                    WHBaseViewVC().openUrl(urlString:UIApplication.openSettingsURLString)
                }, viewController: WHBaseViewVC().getCurrentController()!)
            }
        }
        do {
            try reachability.startNotifier()
        } catch {
            print("Unable to start notifier")
        }
    }
    func sendCheckVersionRequest(){
        DLLog(message: "sendCheckVersionRequest：")
        WHNetworkUtil.shareManager().POST(urlString: URL_judge_ver, parameters: nil) { response in
            let dataDict = response["data"]as? NSDictionary ?? [:]
            
            DLLog(message: "sendCheckVersionRequest：\(dataDict)")
            
            if (dataDict["izCheck"]as? String ?? "") == "Y"{
                //获取app信息
                let infoDictionary : Dictionary = Bundle.main.infoDictionary!
                //版本号
                let buildVersion :String = infoDictionary ["CFBundleVersion"] as! String
                DLLog(message: "buildVersion:\(buildVersion)")
                if (dataDict["version"]as? String ?? "") == buildVersion{
                    UserModel.shared.isCheck = true
                }else{
                    UserModel.shared.isCheck = false
                }
            }else{
                UserModel.shared.isCheck = false
            }

            let token = UserDefaults.standard.string(forKey: whToken)
            if token?.count ?? 0 > 1 {
                self.window?.rootViewController = LLTabBarViewController()
            }else{
                self.window?.rootViewController = LoginVC()
            }
        }
    }
    func sendGetVersionRequest(){
        WHNetworkUtil.shareManager().POST(urlString: URL_Get_Appversion, parameters: nil) { response in
//            DLLog(message: "sendGetVersionRequest：\(response)")

        }
    }
}

// 把要打印的日志写在和AppDelegate同一个等级的方法中,即不从属于AppDelegate这个类，这样在真个项目中才能使用这个打印日志,因为这就是程序的入口,
//这里的T表示不指定message参数类型
func DLLog<T>(message: T, fileName: String = #file, funcName: String = #function, lineNum : Int = #line) {
    
    #if DEBUG
        /**
         * 此处还要在项目的build settings中搜索swift flags,找到 Other Swift Flags 找到Debug
         * 添加 -D DEBUG,即可。
         */
         // 1.对文件进行处理
        let file = (fileName as NSString).lastPathComponent
        // 2.打印内容
        print("[\(file)][\(funcName)](第\(lineNum)行)\(message)")
        
    #endif
}

